/**
 * 
 */
package com.google.code.cisx.gwt.client.session;

/**
 * A client-side user session.
 * 
 * @author <a href='mailto:rahul.thakur.xdev@gmail.com'>Rahul Thakur</a>
 * @since 1.0
 * @version $Id: Session.java 266 2009-01-21 06:38:36Z rahul.thakur.xdev $
 */
public class Session {

  /**
   * Timestamp when this session was created.
   * <p>
   * Defaults to the current time when this {@link Session} instance was created.
   */
  private long created = System.currentTimeMillis();

  /**
   * Timestamp when this session was last accessed/updated.
   * <p>
   * Defaults to the current time when this {@link Session} instance was created.
   */
  private long modified = System.currentTimeMillis();

  /**
   * Authentication Token generated and returned by the server on successful user login.
   */
  private String authenticationToken;

  /**
   * Time interval in milliseconds to keep session alive.
   */
  private final static long timeout = 15 * 60 * 1000;

  private static Session session;

  /**
   * @return the created
   */
  public long getCreated() {
    return created;
  }

  /**
   * @param created
   *          the created to set
   */
  public void setCreated(long created) {
    this.created = created;
  }

  /**
   * @return the modified
   */
  public long getModified() {
    return modified;
  }

  /**
   * @param modified
   *          the modified to set
   */
  public void setModified(long modified) {
    this.modified = modified;
  }

  /**
   * @return the authenticationToken
   */
  public String getAuthenticationToken() {
    return authenticationToken;
  }

  /**
   * @param authenticationToken
   *          the authenticationToken to set
   */
  public void setAuthenticationToken(String authenticationToken) {
    this.authenticationToken = authenticationToken;
  }

  /**
   * Determines if a {@link Session} which is bound is still alive.
   * 
   * @return <code>true</code> if the {@link Session} is still active, else <code>false</code>.
   */
  public boolean isActive() {
    return (System.currentTimeMillis() - getModified()) > timeout;
  }

  private Session() {
    // 
  }

  public static Session newSession() {
    session = new Session();
    session.authenticationToken = "auth-token-test";
    session.created = System.currentTimeMillis();
    session.modified = System.currentTimeMillis();

    return session;
  }

  /**
   * returns a string representation of session
   */
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("Session : ");
    sb.append(hashCode());
    sb.append("[Created : ");
    sb.append(session.created);
    sb.append(", Modified : ");
    sb.append(session.modified);
    sb.append(", Timeout : ");
    sb.append(session.timeout);
    sb.append("]");

    return sb.toString();
  }
}
